import {
    getUserTempId
} from "@/utils/userTempId"
import {
    SET_TOKEN,
    SET_USERINFO,
    DELETE_USERINFO
} from "../constant-type"
import {
    reqUserLogin,
    reqUserInfo,
    reqLogout
} from "@/api"
import {
    getLocalToken,
    setLocalToken,
    removeLocalToken
} from "@/utils/token"
const state = {
    userTempId: getUserTempId(),
    token: getLocalToken() || "",
    userInfo: {}
}
const mutations = {
    //设置token的回调函数
    [SET_TOKEN](state, payload) {
        state.token = payload.token
        setLocalToken(payload.token)
    },
    //设置用户信息的回调函数
    [SET_USERINFO](state, payload) {
        state.userInfo = payload.userInfo
    },
    // 删除用户信息的回调函数
    [DELETE_USERINFO](state){
        // 清空仓库的token
        state.token = ""
        // 清除本地的token
        removeLocalToken()
        // 清除用户信息
        state.userInfo = {}; 
    }
}
const actions = {
    // 请求获取token
    async getTokenAsync({
        commit
    }, userInfo) {
        try {
            // 调用请求登录的接口，将请求回来的结果赋值给re
            const re = await reqUserLogin(userInfo)
            // console.log(re,"re");
            // 调用mutations中的设置token方法，将请求回来的token作为参数传递过去
            commit(SET_TOKEN, {
                token: re.token
            })
        } catch (e) {
            alert(e.message)
            // 此处必须返回一个失败的promise否则鉴权接收不到失败的promise不能做处理
            return Promise.reject()
        }
    },
    // 获取用户信息
    async getUserInfo({
        commit
    }) {
        try {
            const re = await reqUserInfo()
            // console.log(re, "re");
            commit(SET_USERINFO, {
                userInfo: re
            })
        } catch (e) {
            alert(e.message)
            // 此处必须返回一个失败的promise否则鉴权接收不到失败的promise不能做处理
            return Promise.reject()
        }
    },

    // 退出登录
    async getLogout({commit}) {
        try {
            await reqLogout()
            alert("退出登录成功");
            //清理数据
            commit(DELETE_USERINFO);
        } catch (e) {
            alert(e.message)
        }
    },

    // 退出登录的actions
    logoutAsync({commit}){
        // console.log("out");
        commit(DELETE_USERINFO)
    }
}


export default {
    namespaced: true,
    state,
    mutations,
    actions,
}